<template>
  <div class="form-address-international">

    <div class="form-address-picker" :class="[!disableMap && !internationalGray ? 'bbx-form-cell-item' : 'bbx-form-cell-item']">
      <base-dist-picker-international 
        ref="baseDistPickerInternational"
        :disabled="disabled" 
        :country-clearable="countryClearable"
        @input="handleCitySelectorChange" 
        :value="distValue" 
        :showDefaultCountry="showDefaultCountry"
        :placeholder="placeholder"
        :module="module"
      />
      <el-button type="plain-third" @click="chooseMap" v-if="!disableMap && !internationalGray" class="action-btn" :disabled="disabled">{{$t('common.form.preview.address.choosAddressInMap')}}</el-button>
    </div>

    
    <div class="form-address-picker form-address-picker-des bbx-form-cell-item" v-if="!toggle">
      <input
        type="text"
        :value="detail"
        @input="addressInput"
        :maxlength="maxlength"
        :disabled="disabled"
        :id="`form_${field.fieldName}`"
        autocomplete="off"
        :placeholder="$t('common.placeholder.inputDetailAddress')"
      />
      <el-button type="plain-third" class="action-btn" @click="toggleModal">{{$t('common.form.preview.address.resolve')}}</el-button>
    </div>

    <base-modal :show.sync="visible" :title="$t('common.form.preview.address.resolve')" class="form-address-modal">
      <textarea v-model.trim="copy" :placeholder="$t('common.form.preview.address.copyTips')" maxlength="1000"></textarea>
      <el-button type="primary" @click="analyze" :disabled="!copy.length || pending">{{$t('common.base.parse')}}</el-button>
    </base-modal>
  </div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';
import addressParseMixin from './mixin';
import { FORM_FIELD_TEXT_MAX_LENGTH } from '@src/model/const/Number.ts';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage();
// api
import { getServerCachApi } from '@src/api/GuideApi'
const countryCacheKey = 'INTERNATIONAL_DIST_COUNTRY'

export default {
  name: 'form-address',
  mixins: [FormMixin,addressParseMixin],
  props: {
    addressBackup: {
      type: Object,
      default: () => ({})
    },  
    value: {
      type: Object,
      default(){
        let value = {
          /**
           * value值必须包含以下值:
           * country: String,
           * province: String,
           * city: String,
           * dist: String,
           * address: String
           * 
           * 以下值可选：
           * latitude： [String,Number],
           * longitude: [String,Number],
           * addressType: Number
           */
        };
          
        return value
      }
    },

    // 工单客户关联字段清除位置信息时候不调用update
    taskDisableUpdate: {
      type: Boolean,
      default: false
    },

    // 是否展示解析地址
    toggle: {
      type: Boolean,
      default: false
    },

    /** 是否启禁用图选址 */
    disableMap: {
      type: Boolean,
      default: false
    },

    // 是否默认选中中国
    showDefaultCountry: {
      type: Boolean,
      default: true
    },
    countryClearable: {
      type: Boolean,
      default: false
    },
    // 模块
    module: {
      type: String,
      default: '',
    },
  },

  data() {
    return {
      internationalGray,
      distValue: [],
      detail: '',
      maxlength: FORM_FIELD_TEXT_MAX_LENGTH
    }
  },
  computed: {
    /** 是否需要获取街道（客户模块&&未开启国际化&&街道灰度） */
    isNeedGetStreet() {
      const mode = this.field?.tableName || '';
      return mode == 'customer' && !this.internationalGray && this.isOpenAddressStreet;
    },
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      async handler(newValue) {
        // 老数据country为空字符串
        let { country = "", province, city, dist , street = ''} = newValue || {};
        // 街道灰度兼容
        let nStreet = this.isNeedGetStreet ? street : '';
        let newDist = [province, city, dist, nStreet].filter(Boolean);
        if (country || newDist.length) {
          this.distValue = [ country || '', ...newDist ]
        } else {
          this.distValue = []
        }
        if(!country) {
          // 获取国家缓存
          const _country = await this.getCountryCache()
          if(_country){
            this.distValue[0] = _country
          }
        }
        this.detail = newValue?.address || ''
      }
    }
  },

  methods: {
    // 获取国家缓存
    async getCountryCache(){
      if(this.countryValue) return
      const country = sessionStorage.getItem(countryCacheKey);
      if(country) return country
      const { status, data } = await getServerCachApi(countryCacheKey)
      if(status === 0){
        return data?.[0]?.userConfig
      }
    },
    // 地址输入框input事件
    addressInput(event) {

      let adrBackup = this.addressBackup;

      let newAddress = {
        ...this.value,
        address: event.target.value,
      };

      newAddress.addressType = this.diffAddress(newAddress, adrBackup);

      if (newAddress.addressType) {
        newAddress.latitude = adrBackup.adLatitude || adrBackup.latitude;
        newAddress.longitude = adrBackup.adLongitude || adrBackup.longitude;
      } else {
        newAddress.latitude = '';
        newAddress.longitude = '';
      }

      this.updateValue(newAddress)
    },

    diffAddress(newVal, oldVal) {
      
      const newAdr = this.getAddressString(newVal)
      const oldAdr = this.getAddressString(oldVal)

      return Number(newAdr === oldAdr);
    },

    getAddressString(addressObj){
      const { adCountry, country, adProvince, province, adCity, city, adDist, dist, adAddress, address } = addressObj
      return `${adCountry || country}${adProvince || province}${adCity || city}${adDist || dist}${adAddress || address}`
    },

    handleCitySelectorChange(val) {
      let newAddress = {
        country:'',
        province: '',
        city: '',
        dist: '',
        address: '',
        street: ''
      };

      if(!Array.isArray(val) || !val.length) {
        return this.updateValue(newAddress);
      }

      const [ country = '', province = '', city = '', dist = '', street = ''] = val
      newAddress = {
        ...this.value,
        country,
        province,
        city,
        dist,
        street
      };

      let adrBackup = this.addressBackup;
      newAddress.addressType = this.diffAddress(newAddress, adrBackup);


      if (newAddress.addressType) {
        newAddress.latitude = adrBackup.adLatitude || adrBackup.latitude;
        newAddress.longitude = adrBackup.adLongitude || adrBackup.longitude;
      }

      this.updateValue(newAddress);
    },

    updateValue(newValue) {
      let oldValue = null;
      // 工单客户关联字段清除位置信息时候不调用update
      if(!this.taskDisableUpdate){
        this.$emit('update', {newValue, oldValue, field: this.field});
      }
      this.$emit('input', newValue);
    },

    chooseMap() {
      const point = {
        latitude: this.value.latitude || '',
        longitude: this.value.longitude || '',
      };

      let defaultArea = this.value.province;
      // TODO 国际化待办
      if(this.value.city && ['郊县', '市辖区', '其他'].indexOf(this.value.city) < 0) defaultArea = this.value.city;
      if(this.value.dist) defaultArea = this.value.dist; 

      // 有经纬度用经纬度，没有使用较小的行政单位
      this.$fast.map.picker(point, {defaultArea}).then(result => {
        if (result.status === 1) return;

        let adr = result.data;
        adr.street = this.isNeedGetStreet ? adr.township : '';
        adr.addressType = 1;

        this.$emit('update-address-backup', adr);
        this.updateValue(adr);

        this.$nextTick(()=> {
          this.$refs?.baseDistPicker?.setValue(this.distValue);
        });
      })
        .catch(err => console.error(err));
    },

    getValue(){
      return this.value;
    }
  }
}
</script>

<style lang="scss">
.form-address-international {
  input {
    width: 100%;
  }

  .el-input__inner:hover {
    border-color: $color-primary;
  }

  .base-dist-picker {
    flex-grow: 1;
    .el-cascader {
      width: 100%;
    }
  }
}
.form-address-picker{
  display: flex;
  justify-content: space-between;

  .form-address-picker {
    margin-top: 10px;
  }

  .form-item, .form-text {
    width: 400px;
  }
}
</style>
